const express = require("express");
const Result = require('../models/Result')
const memberUser = require('../services/memberUser');
const { md5 , decoded ,checkMobile } = require("../utils");
const { PWD_SALT , PRIVATE_KEY , USER_JWT_EXPIRED } = require("../utils/constant");
const jwt = require("jsonwebtoken")
const Boom = require('boom');
const { validationResult } = require("express-validator");

const router = express.Router();





router.post('/login',function(req,res,next){
    let data = req.body
    if(!checkMobile(data.phone)){
        new Result(null,'请输入正确的手机格式').fail(res)
        return;
    }

    if(data.verify_code==''){
        new Result(null,'验证码不能为空！').fail(res)
        return;
    }
    memberUser.isUser(data.phone).then(user=>{
        if(user==null){
            var name = '用户_'+data.phone;
            
            var touxiang = "https://huijiaoe.oss-cn-chengdu.aliyuncs.com/img/touxiang.png?versionId=CAEQRxiBgMCg3.qjxBciIDZlNWY4ODY1YzhiODQ3ZDA4MjdhMGI0OWIxNDk4MjY5"
            memberUser.addUser({
                'phone':data.phone,
                'nickname':name,
                'avatar':touxiang,
                'sign':'这个人很懒什么都没有写'
            }).then((data)=>{
                const token = jwt.sign( //登录成功生成token
                    {'uid':data.insertId},
                    PRIVATE_KEY,
                    {expiresIn:USER_JWT_EXPIRED}
                )
                new Result({token},'登录成功!').success(res)
            }).catch(err=>{
                next(Boom.badImplementation(err))
            })
            
        }else{
            const token = jwt.sign( //登录成功生成token
                {'uid':user.id},
                PRIVATE_KEY,
                {expiresIn:USER_JWT_EXPIRED}
            )
            new Result({token},'登录成功!').success(res)
        }
        
    })
})



Date.prototype.Format = function (fmt) { // author: meizz
var o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "h+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    "S": this.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

router.get('/getUserInfo',function(req,res){
    const decode = decoded(req)
    if(decode && decode.uid){
        
        var userdata = {
            id:decode.uid,
            last_time:new Date().Format("yyyy-MM-dd hh:mm:ss")
        }
        memberUser.updataUser(userdata).then(user=>{
        })
        
        memberUser.isUser(decode.uid,'uid').then(user=>{
            console.log(user)
            if(user){
                var data = {
                    phone:user.phone,
                    nickname:user.nickname,
                    isVip:user.phone,
                    avatar:user.avatar,
                    balance:user.balance,
                    checkin_count:user.checkin_count,
                    email:user.email,
                    goldcoin:user.goldcoin,
                    id:user.id,
                    sign:user.sign,
                    disable_time:user.disable_time,
                    is_disable:user.is_disable,
                    vipstatus:user.vipstatus,
                    sf_code:user.sf_code,
                }
                new Result(data,'用户信息查询成功').success(res)
            }else{
                new Result('用户信息查询失败').fail(res)
            }
            
        })
    }else{
        new Result('用户信息查询失败').fail(res)
    }
})

router.post('/updataUser',function(req,res,next){//更新用户
    const decode = decoded(req)
    if(decode && decode.uid){
        console.log(req.body)
        req.body.id =  decode.uid
        memberUser.updataUser(req.body).then(()=>{
            new Result(null,'更新成功').success(res)
        }).catch(err=>{
            next(Boom.badImplementation(err))
        })
    }
})



router.post('/userInfo',function(req,res){
    let data = req.body	
    const decode = decoded(req)
    if(decode && decode.uid){
        data.user_id = decode.uid
        memberUser.userInfo(data).then(user=>{
            if(user){
                if(data.id == decode.uid){
                    user.isUser=1
                }
                new Result(user,'用户信息查询成功').success(res)
            }else{
                new Result(null,'用户信息查询失败').fail(res)
            }
            
        })
    }else{
        memberUser.userInfo(data).then(user=>{
            user.relation_type='0'
            if(user){
                new Result(user,'用户信息查询成功').success(res)
            }else{
                new Result(null,'用户信息查询失败').fail(res)
            }
            
        })
    }
})


router.post('/followUser',function(req,res){//关注用户
    let data = req.body	
    const decode = decoded(req)
    if(decode && decode.uid){
        data.user_id = decode.uid
        if(decode.uid == data.follower_id){
            new Result(null,'不能自己关注自己!').fail(res)
            return
        }
        memberUser.followUser(data).then(user=>{
            if(data.relation_type==1){
                new Result(user,'关注成功！').success(res)
            }else if(data.relation_type==0){
                new Result(null,'取消关注!').success(res)
            }else{
                new Result(null,'操作失败!').fail(res)
            }
        })
    }
})

router.post('/getFans',function(req,res){
    let data = req.body	
    memberUser.getFans(data).then(user=>{
        if(user){
            new Result(user,'用户粉丝查询成功').success(res)
        }else{
            new Result(null,'用户粉丝查询失败').fail(res)
        }
        
    })
})

router.post('/getFollower',function(req,res){
    let data = req.body	
    memberUser.getFollower(data).then(user=>{
        if(user){
            new Result(user,'用户关注列表查询成功').success(res)
        }else{
            new Result(null,'用户关注列表查询失败').fail(res)
        }
        
    })
})

router.post('/updatefriends',function(req,res){//添加好友
    let data = req.body	
    const decode = decoded(req)
    if(decode && decode.uid){
        
        data.uid = decode.uid
        data.msg = data.msg
        data.updated_at = new Date().Format("yyyy-MM-dd hh:mm:ss")
        if(decode.uid == data.fid){
            new Result(null,'不能自己给自己发消息!').fail(res)
            return
        }
        memberUser.updatefriends(data).then(user=>{
            new Result(null,'添加成功!').success(res)
        })
    }else{
        new Result('用户信息查询失败').fail(res)
    }
})

router.post('/getFriends',function(req,res){//查询好友
    let data = req.body	
    const decode = decoded(req)
    if(decode && decode.uid){
        data.uid = decode.uid
        memberUser.getFriends(data).then(user=>{
            new Result(user,'查询成功!').success(res)
        })
    }else{
        new Result('用户信息查询失败').fail(res)
    }
})

router.post('/getOneFriend',function(req,res){//获取单个好友数据
    let data = req.body	
    const decode = decoded(req)
    if(decode && decode.uid){
        data.uid = decode.uid
        memberUser.getOneFriend(data).then(user=>{
            new Result(user,'查询成功!').success(res)
        })
    }else{
        new Result('用户信息查询失败').fail(res)
    }
})



router.post('/newUpdateFriend',function(req,res){//给单个好友更新数据
    let data = req.body	
    const decode = decoded(req)
    if(decode && decode.uid){
        data.uid = decode.uid
        memberUser.newUpdateFriend(data).then(user=>{
            new Result(user,'更新成功!').success(res)
        })
    }else{
        new Result('用户信息查询失败').fail(res)
    }
})

router.post('/getHistoryMsg',function(req,res){//获取会话历史记录
    let data = req.body	
    const decode = decoded(req)
    if(decode && decode.uid){
        data.fromId = decode.uid
        memberUser.getHistoryMsg(data).then(user=>{
            new Result(user,'获取成功!').success(res)
        })
    }else{
        new Result('用户信息查询失败').fail(res)
    }
})


router.post('/UpdataThemeMsg',function(req,res){//更新空间背景
    let data = req.body	
    const decode = decoded(req)
    if(decode && decode.uid){
        data.uid = decode.uid
        memberUser.UpdataThemeMsg(data).then(user=>{
            new Result(user,'更新成功!').success(res)
        })
    }else{
        new Result('用户信息查询失败').fail(res)
    }
})


router.post('/pay',function(req,res){//支付
    let data = req.body	
    const decode = decoded(req)
    if(decode && decode.uid){
        data.id = decode.uid
        memberUser.isUser(decode.uid,'uid').then(user=>{
            if(user){
                data.balance = (Number(user.balance) + Number(data.money))
                delete data.type
                delete data.money
                memberUser.updataUser(data).then(user=>{
                    new Result(user,'支付成功!').success(res)
                })
            }else{
                new Result('用户信息查询失败').fail(res)
            }
        })
       
    }else{
        new Result('用户查询失败').fail(res)
    }
})












module.exports = router